package com.example.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

//udp
public class DatagramChannelDemo {
    public static void main(String[] args) {
        ArrayList<Integer> objects = new ArrayList<>(1000);
        for (int i = 0; i < 1000; i++) {
            objects.add(i);
        }
        System.out.println(objects.subList(0, 100));
        System.out.println(objects.subList(100, 200));
    }

    @Test
    public void sendDatagram() throws IOException, InterruptedException {
        DatagramChannel datagramChannel = DatagramChannel.open();
        InetSocketAddress localhost = new InetSocketAddress("localhost", 9999);
        while (true) {
            ByteBuffer buffer = ByteBuffer.wrap("发送一条信息".getBytes(StandardCharsets.UTF_8));
            datagramChannel.send(buffer, localhost);
            Thread.sleep(2000);
        }
    }

    @Test
    public void receiveDatagram() throws IOException, InterruptedException {
        DatagramChannel datagramChannel = DatagramChannel.open();
        InetSocketAddress localhost = new InetSocketAddress(9999);
        while (true) {
            //   ByteBuffer buffer = ByteBuffer.wrap("发送".getBytes(StandardCharsets.UTF_8));
            datagramChannel.bind(localhost);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (true) {
                buffer.clear();
                SocketAddress socketAddress = datagramChannel.receive(buffer);
                buffer.flip();
                System.out.println(socketAddress.toString());
                System.out.println(Charset.forName("UTF-8").decode(buffer));
            }
        }
    }
}
